<?php
/**
 * (logic) 报告解析失败（未解析）
 */

namespace App\Logic\MonthlyReport;

use App\Models\Basics\SysCountry;
use App\Models\MonthlyReport\Tmp\TmpPCPlanFee;
use App\Models\Product\ProductAmazonSku;
use App\Models\MonthlyReport\Payment\LongTermStorage;
use App\Models\MonthlyReport\Payment\RemovalOrder;
use App\Models\MonthlyReport\Tmp\TmpAds;
use App\Models\MonthlyReport\Tmp\TmpDSP;
use App\Models\MonthlyReport\Tmp\TmpPIcFee;
use App\Models\MonthlyReport\Tmp\TmpPReFee;
use App\Models\MonthlyReport\Tmp\TmpPSales;
use App\Models\MonthlyReport\Tmp\TmpPThFee;
use App\Models\MonthlyReport\Tmp\TmpPTotal;
use App\Models\MonthlyReport\Tmp\TmpVBC;
use Illuminate\Support\Facades\DB;
class ParseMiss
{
    public static function parse($action)
    {
        $date = date('Y-m-01',strtotime('midnight first day of -1 month'));
        $countryOption = array_flip(SysCountry::options()->toArray());
        self::exeMiss($action,$countryOption,$date);
    }

    private static function exeMiss($action,$countryOption,$date){
        $existCountry = [];
        $existPas = [];
        $existMiss = [];
        $exist = [];
        $class = self::$_class[$action];
        $field = self::$_field[$action];
        $class::select('country',$field . ' as sku')
            ->where('report_date',$date)
            ->whereNotNull($field)
            ->orderBy('id')
            ->chunk(2000, function ($items) use (&$existCountry,&$existPas,&$existMiss,&$exist,$countryOption,$date,$action){
                $miss = [];
                $time = date('Y-m-d H:i:s');
                foreach ($items as $item){
                    if(empty($item->sku))continue;
                    $value = $item->country .'_' . $item->sku . '_' . $action;
                    if(!array_key_exists($value,$exist)){
                        $count = DB::table('mr_parse_miss')
                            ->where('country',$item->country)
                            ->where('sku',$item->sku)
                            ->where('sour',$action)
                            ->count();
                        $exist[$value] = $count;
                    }
                    if($exist[$value] > 0)continue;
                    $temp = [];
                    if(!array_key_exists($item->country,$existCountry)){
                        if(!array_key_exists($item->country,$countryOption)){
                            $existCountry[$item->country] = 0;
                        }else{
                            $existCountry[$item->country] = $countryOption[$item->country];
                        }
                    }
                    if($existCountry[$item->country] == 0){
                        if(!in_array($value,$existMiss)){
                            $existMiss[] = $value;
                            $temp['country'] = $item->country;
                            $temp['sku'] = $item->sku;
                            $temp['desc'] = "系统未匹配到该国家";
                            $temp['sour'] = $action;
                            $temp['created_at'] = $time;
                            $temp['updated_at'] = $time;
                            $miss[] = $temp;
                        }
                        continue;
                    }
                    $countryId = $existCountry[$item->country];
                    $key = $countryId.'_'.$item->sku;
                    if(!array_key_exists($key,$existPas)){
                        $count = ProductAmazonSku::query()
                            ->where('country_id',$countryId)
                            ->where('seller_sku',$item->sku)
                            ->count();
                        $existPas[$key] = $count;
                    }
                    if($existPas[$key] == 0){
                        if(!in_array($value,$existMiss)){
                            $existMiss[] = $value;
                            $temp['country'] = $item->country;
                            $temp['sku'] = $item->sku;
                            $temp['desc'] = "系统未匹配到该国家的产品";
                            $temp['sour'] = $action;
                            $temp['created_at'] = $time;
                            $temp['updated_at'] = $time;
                            $miss[] = $temp;
                        }
                        continue;
                    }
                }
                if(!empty($miss)){
                    try{
//                        $i = 0;
//                        $num = 1;
//                        while(true){
//                            if(empty($miss))break;
//                            $_miss = array_splice($miss,$i,$num);
                            DB::beginTransaction();
                            DB::table('mr_parse_miss')->insert($miss);
                            DB::commit();
//                        }
                    }catch (\Exception $e){
                        DB::rollBack();
                        report($e);
                    }
                }
            });
    }

    private static $_class = [
        'sa' => TmpPSales::class,
        'c-plan' => TmpPCPlanFee::class,
        're' => TmpPReFee::class,
        'th' => TmpPThFee::class,
        'lts' => LongTermStorage::class,
        'ic' => TmpPIcFee::class,
        'ro' => RemovalOrder::class,
        'm-ads' => TmpAds::class ,
        'vbc' => TmpVBC::class,
        'dsp' => TmpDSP::class,
        'to' => TmpPTotal::class
    ];

    private static $_field = [
        'sa' => 'sku',
        'c-plan' => 'sku',
        're' => 'sku',
        'th' => 'sku',
        'lts' => 'sku',
        'ic' => 'sku',
        'ro' => 'sku',
        'm-ads' => 'seller_sku',
        'vbc' => 'sku',
        'dsp' => 'seller_sku',
        'to' => 'sku',
    ];

    public static $_file = [
        'sa' => 'Payment-销售额',
        'dsp' => 'DSP',
        're' => 'Payment-退货费',
        'th' => 'Payment-第三方发货FBA费',
        'lts' => 'LongTermStorage',
        'ic' => 'Payment-库存补偿费',
        'ro' => 'RemovalOrderDetail',
        'm-ads' => 'Advertised',
        'vbc' => 'Video&BrandsCampaign',
        'ie' => 'InventoryEventDetail',
        'to' => 'Payment-Total ',
    ];
}
